<!DOCTYPE html>
          <head>
        <meta charset="utf-8">
            
            <title>
                「Flask」0x01FlaskMail | ttdevs
            </title>
            <meta content="width=device-width, initial-scale=1" name="viewport">
            <meta name="theme-color" content="#4184f3">
            
            
            <link href="/favicon.ico" rel="icon"/>
            

            <link rel="stylesheet" href="/css/highlight.light.css">
            <link rel="stylesheet" href="/css/prism-customize.css">
            <link rel="stylesheet" href="/css/nav-icon.css">
            <link rel="stylesheet" href="/css/waves.min.css">
            <link rel="stylesheet" href="/css/jquery.tocify.css">
            <link rel="stylesheet" href="/css/main.css">
            <link rel="stylesheet" href="/css/nav-indicator.css">
            
  

  
  <!-- 谷歌统计 -->
  <script>
    (function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
    (i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
    m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
    })(window,document,'script','//www.google-analytics.com/analytics.js','ga');

    ga('create', 'UA-97465173-1', 'auto');
    ga('send', 'pageview');

  </script>
  
            </meta>
        </meta>
    </head>

    <body>
        <header>
            <!-- cover image or sth. -->
        </header>
        <div id="main" class="m-scene">
            
<div class="nav-wrapper">

    <div class="container">
        <nav>
            <div class="logo wave">
                <a href="/" id="logo">
                    ttdevs
                </a>
            </div>
            <div class="nav-toggle-icon" >
                <div class="material-hamburger">
                    <span>
                    </span>
                    <span>
                    </span>
                    <span>
                    </span>
                </div>
            </div>
            <div class="menu-wrapper">
                <div class="nav-indicator">
                </div>
                <ul class="menus">
                    
                     
                        <li>
                            <a class="wave " href="/">
                                首页
                            </a>
                        </li>
                     
                        <li>
                            <a class="wave " href="/archives">
                                归档
                            </a>
                        </li>
                     
                        <li>
                            <a class="wave " href="/about">
                                关于
                            </a>
                        </li>
                     
                    
                   
                </ul>
            </div>
        </nav>
    </div>
</div>
            <div class="container content">
                <div class="scene_element scene_element--fadein">
                    <div class="row">
    <div class="main">
        <article>
          
          <header class="post-header with-cover" style="background-image:url('/1970/01/01/[Flask]0x01FlaskMail/cover.jpg')" >
          
          </header>
          <h1 class="post-title">「Flask」0x01FlaskMail</h1>

          <section class="post-info">
            <span class="post-date">1970/01/01</span>
            
            <span class="post-category">
                <a class="article-category-link" href="/categories/技术/">技术</a>
            </span>
            
            
            <span class="post-tags">
              <ul class="post-tag-list"><li class="post-tag-list-item"><a class="post-tag-list-link" href="/tags/Flask/">Flask</a></li></ul>
            </span>
            
          </section>

          <section class="post-content">
            <h2 id="0x00-简介"><a href="/1970/01/01/[Flask]0x01FlaskMail/#0x00-简介" class="headerlink" title="0x00  简介"></a>0x00  简介</h2><blockquote>
<p>Welcome to Flask-Mail, you can use to send mail in your web site.</p>
</blockquote>
<p>Flask-Mail 提供了一个简单的接口，让我们可以方便的在 Flask 应用中使用 SMTP协议 发送邮件。</p>
<h2 id="0x01-安装"><a href="/1970/01/01/[Flask]0x01FlaskMail/#0x01-安装" class="headerlink" title="0x01 安装"></a>0x01 安装</h2><p><code>pip install Flask-Mail</code></p>
<p>目前最新版本是 0.9.1 ，从 <a href="https://github.com/mattupstate/flask-mail" target="_blank" rel="external">Flask-Mail的github地址</a>可以发现，两年没有更新了。不过这个并不影响我们使用，毕竟发送邮件是个比较成熟的东西，只祈求和最新的Flask不要出现兼容问题即可。</p>
<p>如果你不想使用这个工具，可以找找其他的，不过你会发现，其他的可能更老，也是醉了=_=</p>
<p>如果时间充足，我们可以去读读 Flask-Mail 的源码，你会发现，最终是用系统自带的 smtplib 实现的。</p>
<h2 id="0x02-使用"><a href="/1970/01/01/[Flask]0x01FlaskMail/#0x02-使用" class="headerlink" title="0x02 使用"></a>0x02 使用</h2><p>一句话总结：Flask-Mail 的使用还是相当easy的。</p>
<h3 id="配置"><a href="/1970/01/01/[Flask]0x01FlaskMail/#配置" class="headerlink" title="配置"></a>配置</h3><p>Flask-Mail 使用 Flask 标准的配置 API 进行配置。下面是所有的配置选项：</p>
<ul>
<li>MAIL_SERVER : 默认为 ‘127.0.0.1’</li>
<li>MAIL_PORT : 默认为 25</li>
<li>MAIL_USE_TLS : 默认为 False</li>
<li>MAIL_USE_SSL : 默认为 False</li>
<li>MAIL_DEBUG : 默认为 app.debug</li>
<li>MAIL_USERNAME : 默认为 None</li>
<li>MAIL_PASSWORD : 默认为 None</li>
<li>MAIL_DEFAULT_SENDER : 默认为 None</li>
<li>MAIL_MAX_EMAILS : 默认为 None</li>
<li>MAIL_SUPPRESS_SEND : 默认为 app.testing</li>
<li>MAIL_ASCII_ATTACHMENTS : 默认为 False</li>
</ul>
<p>这个配置的参数我们可以在<a href="https://github.com/mattupstate/flask-mail/blob/master/flask_mail.py" target="_blank" rel="external">这里</a>看到。</p>
<h3 id="初始化"><a href="/1970/01/01/[Flask]0x01FlaskMail/#初始化" class="headerlink" title="初始化"></a>初始化</h3><p>可以使用下面的两种方式进行初始化：</p>
<ul>
<li><p>第一种方式：</p>
<p>  使用传入到 Mail 实例中的应用程序的配置项进行邮件发送</p>
  <figure class="highlight python"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div></pre></td><td class="code"><pre><div class="line"><span class="keyword">from</span> flask <span class="keyword">import</span> Flask</div><div class="line"><span class="keyword">from</span> flask_mail <span class="keyword">import</span> Mail</div><div class="line"></div><div class="line">app = Flask(__name__)</div><div class="line">mail = Mail(app)</div></pre></td></tr></table></figure>
</li>
<li><p>第二种方式：</p>
<p>  使用 Flask 的 current_app 中的配置项进行邮件发送，如果我们有多个 不同配置的应用程序 则使用此种方式比较方便</p>
  <figure class="highlight python"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div></pre></td><td class="code"><pre><div class="line">mail = Mail()</div><div class="line"></div><div class="line">app = Flask(__name__)</div><div class="line">mail.init_app(app)</div></pre></td></tr></table></figure>
</li>
</ul>
<h3 id="发送"><a href="/1970/01/01/[Flask]0x01FlaskMail/#发送" class="headerlink" title="发送"></a>发送</h3><p>发送之前我们需要先构建一个 Message 对象，如下：</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div></pre></td><td class="code"><pre><div class="line"><span class="keyword">from</span> flask_mail <span class="keyword">import</span> Message</div><div class="line"></div><div class="line">msg = Message(<span class="string">"Hello Flask"</span>, sender=<span class="string">"ttdevs@gmail.com"</span>,  recipients=[<span class="string">"ttdevs@live.com"</span>])</div></pre></td></tr></table></figure>
<p>我们也可以同时指定多个收件人</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div></pre></td><td class="code"><pre><div class="line">msg.recipients = [<span class="string">"ttdevs@gmail.com"</span>, <span class="string">"ttdevs@foxmail.com"</span>]</div><div class="line">msg.add_recipient(<span class="string">"ttdevs@live.com"</span>)</div></pre></td></tr></table></figure>
<p>如果我们配置了 <code>MAIL_DEFAULT_SENDER</code> 字段，就可以不再设置 sender ，这个时候会使用  <code>MAIL_DEFAULT_SENDER</code> 中指定的发件人，像这样：</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><div class="line">1</div></pre></td><td class="code"><pre><div class="line">msg = Message(<span class="string">"Hello Flask"</span>, recipients=[<span class="string">"ttdevs@live.com"</span>])</div></pre></td></tr></table></figure>
<p>如果我们希望在收件列表中显示一个名字，可以通过一个二元祖来指定：</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><div class="line">1</div></pre></td><td class="code"><pre><div class="line">msg = Message(<span class="string">"Hello"</span>, sender=(<span class="string">"ttdevs"</span>, <span class="string">"ttdevs@live.com"</span>))</div></pre></td></tr></table></figure>
<p>同时， 我们还可以指定下面两个字段：</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div></pre></td><td class="code"><pre><div class="line">msg.body = <span class="string">"this is body string"</span></div><div class="line">msg.html = <span class="string">"&lt;h2&gt;this is html message&lt;/b&gt;"</span></div></pre></td></tr></table></figure>
<p>最后就是发送：</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><div class="line">1</div></pre></td><td class="code"><pre><div class="line">mail.send(msg)</div></pre></td></tr></table></figure>
<p>发送完毕后，与邮件服务器的链接就会关闭。</p>
<h3 id="发送大量邮件"><a href="/1970/01/01/[Flask]0x01FlaskMail/#发送大量邮件" class="headerlink" title="发送大量邮件"></a>发送大量邮件</h3><p>如果我们一次发送大量的邮件，可以通过下面的方式发送：</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div></pre></td><td class="code"><pre><div class="line"><span class="keyword">with</span> mail.connect() <span class="keyword">as</span> conn:</div><div class="line">    <span class="keyword">for</span> user <span class="keyword">in</span> users:</div><div class="line">        message = <span class="string">'...'</span></div><div class="line">        subject = <span class="string">"hello, %s"</span> % user.name</div><div class="line">        msg = Message(recipients=[user.email],</div><div class="line">                      body=message,</div><div class="line">                      subject=subject)</div><div class="line">        conn.send(msg)</div></pre></td></tr></table></figure>
<p>与电子邮件服务器的连接会一直保持直到所有的邮件都已经发送完毕才会断开。</p>
<blockquote>
<p>Some mail servers set a limit on the number of emails sent in a single connection. You can set the max amount of emails to send before reconnecting by specifying theMAIL_MAX_EMAILS setting.</p>
</blockquote>
<h3 id="添加附件"><a href="/1970/01/01/[Flask]0x01FlaskMail/#添加附件" class="headerlink" title="添加附件"></a>添加附件</h3><p>在邮件中添加附件同样非常简单：</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div></pre></td><td class="code"><pre><div class="line">image = <span class="string">'umbrella.jpg'</span></div><div class="line"><span class="keyword">with</span> app.open_resource(image) <span class="keyword">as</span> fp:</div><div class="line">    msg.attach(image, <span class="string">'image/jpg'</span>, fp.read())</div></pre></td></tr></table></figure>
<h2 id="0x03-Demo"><a href="/1970/01/01/[Flask]0x01FlaskMail/#0x03-Demo" class="headerlink" title="0x03 Demo"></a>0x03 Demo</h2><p>下面是一个简单的Demo，装好相关的类库， 直接可以跑，大家可以参考：</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div><div class="line">15</div><div class="line">16</div><div class="line">17</div><div class="line">18</div><div class="line">19</div><div class="line">20</div><div class="line">21</div><div class="line">22</div><div class="line">23</div><div class="line">24</div><div class="line">25</div><div class="line">26</div><div class="line">27</div><div class="line">28</div><div class="line">29</div><div class="line">30</div><div class="line">31</div><div class="line">32</div></pre></td><td class="code"><pre><div class="line"><span class="comment">#!/usr/bin/env python3</span></div><div class="line"><span class="comment"># coding:utf-8</span></div><div class="line"></div><div class="line"><span class="keyword">from</span> flask <span class="keyword">import</span> Flask</div><div class="line"><span class="keyword">from</span> flask_mail <span class="keyword">import</span> Mail</div><div class="line"><span class="keyword">from</span> flask_mail <span class="keyword">import</span> Message</div><div class="line"></div><div class="line">app = Flask(__name__)</div><div class="line">app.config[<span class="string">'MAIL_SERVER'</span>] = <span class="string">'smtp.qq.com'</span></div><div class="line">app.config[<span class="string">'MAIL_PORT'</span>] = <span class="number">465</span></div><div class="line">app.config[<span class="string">'MAIL_USE_SSL'</span>] = <span class="keyword">True</span></div><div class="line">app.config[<span class="string">'MAIL_USERNAME'</span>] = <span class="string">'iot.raspi@qq.com'</span></div><div class="line">app.config[<span class="string">'MAIL_PASSWORD'</span>] = <span class="string">'********'</span></div><div class="line">app.config[<span class="string">'MAIL_DEFAULT_SENDER'</span>] = <span class="string">'iot.raspi@qq.com'</span></div><div class="line"></div><div class="line">mail = Mail(app)</div><div class="line"></div><div class="line"></div><div class="line"><span class="meta">@app.route('/')</span></div><div class="line"><span class="function"><span class="keyword">def</span> <span class="title">welcome</span><span class="params">()</span>:</span></div><div class="line">    msg = Message(<span class="string">'这是一封测试邮件Header'</span>, recipients=[<span class="string">'56532799@qq.com'</span>])</div><div class="line">    msg.body = <span class="string">'这是一封测试邮件 bodyer'</span></div><div class="line">    msg.html = <span class="string">'这是一封测试邮件 htmler'</span></div><div class="line">    image = <span class="string">'umbrella_伞.jpg'</span></div><div class="line">    <span class="keyword">with</span> app.open_resource(image) <span class="keyword">as</span> fp:</div><div class="line">        msg.attach(image, <span class="string">'image/jpg'</span>, fp.read())</div><div class="line">    mail.send(msg)</div><div class="line">    <span class="keyword">return</span> <span class="string">'Hello world!'</span></div><div class="line"></div><div class="line"></div><div class="line"><span class="keyword">if</span> __name__ == <span class="string">'__main__'</span>:</div><div class="line">    app.run(debug=tuple)</div></pre></td></tr></table></figure>
<h3 id="邮件参数说明"><a href="/1970/01/01/[Flask]0x01FlaskMail/#邮件参数说明" class="headerlink" title="邮件参数说明"></a>邮件参数说明</h3><p>上面的Demo中用到QQ邮箱，这里简单介绍下。由于QQ邮箱需要安全验证，所以我们配置下面几个参数：</p>
<ul>
<li><p>MAIL_SERVER</p>
<p>  SMTP地址：smtp.qq.com</p>
</li>
<li><p>MAIL_PORT</p>
<p>  由于需要安全验证，所以此处用465</p>
</li>
<li><p>MAIL_USE_SSL：True</p>
<p>  SSL，走加密方式</p>
</li>
<li><p>MAIL_USERNAME</p>
<p>  iot.raspi@qq.com</p>
</li>
<li><p>MAIL_PASSWORD</p>
<p>  这个地方我们需要使用授权码：<br>  打开 <code>QQ邮箱</code> &gt; <code>设置</code> &gt; <code>POP3/IMAP/SMTP/Exchange/CardDAV/CalDAV服务</code> &gt; <code>生成授权码</code></p>
</li>
</ul>
<p>最后别忘了打开SMTP服务～～</p>
<h2 id="0x04-其他"><a href="/1970/01/01/[Flask]0x01FlaskMail/#0x04-其他" class="headerlink" title="0x04 其他"></a>0x04 其他</h2><p>（TODO 留坑，其实暂时还没学到～～）</p>
<h3 id="单元测试"><a href="/1970/01/01/[Flask]0x01FlaskMail/#单元测试" class="headerlink" title="单元测试"></a>单元测试</h3><h3 id="禁止发送邮件"><a href="/1970/01/01/[Flask]0x01FlaskMail/#禁止发送邮件" class="headerlink" title="禁止发送邮件"></a>禁止发送邮件</h3><h3 id="头注入"><a href="/1970/01/01/[Flask]0x01FlaskMail/#头注入" class="headerlink" title="头注入"></a>头注入</h3><h3 id="信号量"><a href="/1970/01/01/[Flask]0x01FlaskMail/#信号量" class="headerlink" title="信号量"></a>信号量</h3><h3 id="API"><a href="/1970/01/01/[Flask]0x01FlaskMail/#API" class="headerlink" title="API"></a>API</h3><h2 id="0xFF-参考"><a href="/1970/01/01/[Flask]0x01FlaskMail/#0xFF-参考" class="headerlink" title="0xFF 参考"></a>0xFF 参考</h2><ol>
<li><a href="http://pythonhosted.org/Flask-Mail/" target="_blank" rel="external">http://pythonhosted.org/Flask-Mail/</a></li>
<li><a href="http://www.pythondoc.com/flask-mail/" target="_blank" rel="external">http://www.pythondoc.com/flask-mail/</a></li>
<li><a href="https://pypi.python.org/pypi/Flask-Mail/" target="_blank" rel="external">https://pypi.python.org/pypi/Flask-Mail/</a></li>
</ol>
<p><img src="https://raw.githubusercontent.com/ttdevs/ttdevs.github.io/common/images/logo.png" alt="Create by ttdevs"></p>

          </section>
        </article>
        

       
        <div class="pager">
          
            <a class="post-prev pager-item" href="/1970/01/01/[Android]对App进行代码混淆/" >
              <strong class="article-nav-caption">上一篇</strong>
              <p class="post-nav-title">「Android」对App进行代码混淆</p>
            </a>
          
          
            <a class="post-next pager-item" href="/1970/01/01/[Flask]0x03树莓派上使用Nginx和uWSGI部署Flask应用/">
              <strong class="article-nav-caption">下一篇</strong>
              <p class="post-nav-title">「Flask」0x03树莓派上使用Nginx和uWSGI部署Flask应用</p>
            </a>
          
        </div>
        

         <!-- comments -->
        <div class="comment-section">
  
    


</div>

    </div>
    
    <aside>
        <div id="toc">
        </div>
    </aside>
    
</div>

                </div>
            </div>
        </div>
        <footer class="footer">
    <p>由<a href="http://hexo.io/" target="_blank">Hexo</a>强力驱动，搭载<a href="https://github.com/wayou/hexo-theme-gstyle">gstyle</a>主题</p>
    <p>
        &copy; 2017 ttdevs
    </p>
</footer>
<script src="/lib/jquery.js"></script>
<script src="/lib/waves.js"></script>
<script src="/lib/jquery-ui.js"></script>
<script src="/lib/jquery.tocify.js"></script>
<script src="/js/main.js"></script>

    </body>
</html>
